var zTreeObj = undefined;
var typeNodeSelected = undefined;
$(function () {
    fnInitView();

    fnLoadFrequentlyList();

    fnLoadTree();

    fnRefreshSession();
})

function fnInitView() {
    document.onkeydown = function (event) {
        var e = event || window.event || arguments.callee.caller.arguments[0];
        if (e && e.keyCode == 13) { // enter 键
            if ($('.search-text').is(':focus') || $('.search-type').is(':focus'))
                fnSearchContent();
            else
                fnSearchKeyword();
        }
    };

    var linkMenu = $('.link-menu').menu({
        onClick: function (item) {
            var target = linkMenu.data('target');
            var id = $(target).data('linkid');
            var link = $(target).data('link');
            var name = $(target).data('name');
            var title = $(target).attr('title');
            var typeid = $(target).data('typeid');

            switch (item.text) {
                case "打开": {
                    fnOpenUrl(id, link);
                }
                    break;
                case "修改": {
                    $.post("/api/link/type/" + typeid, function (data) {
                        var typeNode = data.msg;
                        $("#idLinkEditModalLabel").html("编辑链接");
                        $("#idLinkTypeName").data("typeid", typeid).val(typeNode.name);
                        $("#idLinkName").val(name);
                        $("#idLinkURL").val(link);
                        $("#idLinkDescription").val(title);
                        $("#idLinkEditModel").modal("show");
                    }, 'json');
                }
                    break;
                case "删除": {
                    if (confirm("确定删除该链接吗？")) {
                        $.post("/api/link/delete", { linkId: id }, function (data) {
                            if (typeNodeSelected)
                                fnLoadLinks(typeNodeSelected);
                            else {
                                fnLoadFrequentlyList();
                            }
                            fnLoadTree();
                        });
                    }
                }
                    break;
                case "移动": {
                    $("#idLinkMoveName").data('linkid', id).val(name);
                    $("#idLinkMoveNewType").data('typeid', '').val('');
                    $.post("/api/link/type/" + typeid, function (data) {
                        var typeNode = data.msg;
                        $("#idLinkMoveOldType").val(typeNode.name);
                        $("#idLinkMoveModel").modal("show");
                    }, 'json');
                }
                    break;
            }
        }
    });

    $("#btnAddRootType").click(function () {
        $("#idParentTypeName").data('parentid', -1).val("根节点");
    });
    $("#btnSubmitType").click(function () {
        var parentId = $("#idParentTypeName").data("parentid");
        var name = $("#idTypeName").val();
        var description = $("#idTypeDescription").val();
        if (name.length == 0) {
            alert("请输入类型信息");
            return;
        }
        $.post("/api/link/addType", { parentId: parentId, name: name, description: description }, function (data) {
            fnLoadTree();
        }, "json");
    });
    $("#btnSubmitLink").click(function () {
        var typeId = $("#idLinkTypeName").data("typeid");
        var name = $("#idLinkName").val();
        var url = $("#idLinkURL").val();
        var description = $("#idLinkDescription").val();

        if (name.length == 0) {
            alert("请输入名称...");
            return;
        }
        if (url.length == 0) {
            alert("请输入链接地址...");
            return;
        }
        $.post("/api/link/addLink", { typeId: typeId, name: name, url: url, description: description }, function (data) {
            fnLoadTree();
            if (typeNodeSelected)
                fnLoadLinks(typeNodeSelected);
            else {
                fnLoadFrequentlyList();
            }
        }, "json");
    });
    $("#btnLogout").click(function () {
        if (confirm("确定退出吗？")) {
            $.post("/api/login/logout", function (data) {
                location = "/";
            }, "json");
        }
    });
}

function fnSearchContent() {

}

function fnSearchKeyword() {
    var key = $("#idKeyword").val();
    if ($.trim(key) == "") {
        fnLoadFrequentlyList();
        return;
    }
    var $idLinkList = $(".my-link-list").html('<div style="padding:5px 15px;">正在查询...</div>');
    $("#idPanelTitle").html("查询结果");
    $.post("/api/link/search", { key: key }, function (data) {
        fnAppendLinks(undefined, $idLinkList, data.msg);
    }, "json");
}

function fnLoadTree() {
    var setting = {
        async: {
            enable: true,
            url: "/api/link/loadTypes",
            autoParam: ["id=parentId"],
            dataFilter: function (treeId, parentNode, responseData) {
                //console.log(responseData);
                return responseData.msg;
            }
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id"
            },
            key: {
                name: "name",
                title: "description",
                children: "children"
            }
        },
        view: {
            showIcon: false,
            addDiyDom: function (treeId, treeNode) {
                var count = treeNode.count;
                var aObj = $("#" + treeNode.tId + "_span");
                var editStr = "<span class='label label-warning' style='margin:2px 5px;padding:1px;'>" + count + "</span>";
                aObj.append(editStr);
            }
        }
    }

    var tree = $("#idTypeTree").html('<div style="padding:5px 15px;">正在加载类别...</div>');
    var typeMenu = $(".type-menu").menu({
        onClick: function (item) {
            var target = typeMenu.data('target');
            console.log(target);

            var name = target.name;
            var description = target.description;
            var typeid = target.id;
            var parentid = target.parentid;

            switch (item.text) {
                case "添加子类别": {
                    $("#idTypeEditModalLabel").html("新增子类别");
                    $("#idParentTypeName").data("parentid", typeid).val(name);
                    $("#idTypeName").data("typeid", '').val('');
                    $("#idTypeDescription").val('');
                    $("#idParentTypeRow").show();
                    $("#btnAddRootType").show();
                    $("#idTypeEditModel").modal('show');
                }
                    break;
                case "添加链接": {
                    $("#idLinkEditModalLabel").html("添加链接");
                    $("#idLinkTypeName").data("typeid", typeid).val(name);
                    $("#idLinkName").val('');
                    $("#idLinkURL").val('');
                    $("#idLinkDescription").val('');
                    $("#idLinkEditModel").modal("show");
                }
                    break;
                case "编辑": {
                    $("#idTypeEditModalLabel").html("编辑类别");
                    $("#idParentTypeName").data("parentid", '').val('');
                    $("#idTypeName").data("typeid", typeid).val(name);
                    $("#idTypeDescription").val(description);
                    $("#idParentTypeRow").hide();
                    $("#btnAddRootType").hide();
                    $("#idTypeEditModel").modal('show');
                }
                    break;
            }
        }
    });
    $.post("/api/link/loadTypes", { parentId: -1 }, function (data) {
        if (data.code == 0) {
            zTreeObj = $.fn.zTree.init(tree, $.extend({}, setting, {
                edit: {
                    enable: true,
                    showRemoveBtn: false,
                    showRenameBtn: false
                },
                callback: {
                    onCollapse: function (event, treeId, treeNode) {
                        //console.log(treeNode);
                        fnUpdateCollapse(treeNode.id, 1);
                    },
                    onExpand: function (event, treeId, treeNode) {
                        //console.log(treeNode);
                        fnUpdateCollapse(treeNode.id, 0);
                    },
                    onDrop: function (event, treeId, treeNodes, targetNode, moveType, isCopy) {
                        fnDropTypeNode(treeNodes[0], targetNode, moveType);
                    },
                    onRightClick: function (event, treeId, treeNode) {
                        typeMenu.data('target', treeNode).menu('show', {
                            left: event.pageX,
                            top: event.pageY
                        });
                    },
                    onClick: function (event, treeId, treeNode) {
                        typeNodeSelected = treeNode;
                        fnLoadLinks(treeNode);
                    },
                    onAsyncSuccess: function (event, treeId, treeNode, msg) {
                        //console.log(treeNode);

                        var children = treeNode.children || [];
                        $.each(children, function (i, node) {
                            zTreeObj.expandNode(node, node.collapse == 0, false, false, true);
                        });
                    }
                }
            }), data.msg);

            $.fn.zTree.init($("#idLinkTypeMove"), $.extend({}, setting, {
                callback: {
                    onClick: function (event, treeId, treeNode) {
                        $("#idLinkMoveNewType").data('typeid', treeNode.id).val(treeNode.name);
                    }
                }
            }), data.msg);

            var pidNodes = zTreeObj.getNodesByFilter(function (node) {
                return node.level == 0
            }, false);
            //console.log(pidNodes)
            $.each(pidNodes, function (i, node) {
                zTreeObj.expandNode(node, node.collapse == 0, false, false, true);
            });
        }
    }, 'json');
}

function fnDropTypeNode(node, targetNode, moveType) {
    var targetId;
    if (!targetNode)
        targetId = -1;
    else if (node.parentid != targetNode.parentid || moveType == 'inner') {
        if (moveType == 'inner')
            targetId = targetNode.id;
        else
            targetId = targetNode.parentid;
    }
    if (!targetId)
        return;
    $.post("/api/link/moveType", { typeId: node.id, parentId: targetId }, function (data) {
        //fnLoadTree();
    });
}

function fnUpdateCollapse(typeId, state) {
    $.post("/api/link/collapse", { typeId: typeId, state: state });
}

function fnLoadFrequentlyList() {
    var $idLinkList = $(".my-link-list").html('<div style="padding:5px 15px;">正在加载最近使用导航列表...</div>');
    $("#idPanelTitle").html("最近常用");
    $.post("/api/link/frequently", { count: 60 }, function (data) {
        fnAppendLinks(undefined, $idLinkList, data.msg);
    }, "json");
}

function fnLoadLinks(node) {
    var $idLinkList = $(".my-link-list").html('<div style="padding:5px 15px;">正在加载"' + node.name + '"列表...</div>');
    $("#idPanelTitle").html(node.name);
    $.post("/api/link/loadLinks", { typeId: node.id }, function (data) {
        fnAppendLinks(node, $idLinkList, data.msg);
    }, "json");
}

function fnAppendLinks(node, container, list) {
    container.html('');
    list.sort(function (a, b) {
        return a.visitcount <= b.visitcount ? 1 : -1;
    });

    if (list.length == 0) {
        container.html('<div style="text-align:center;font-size:18px;"><span class="label label-info">当前类型无导航链接！</span></div>');
        return;
    }
    var sl = '<table class="table table-bordered"><tr>';
    var colspan = fnGetColspan(list.length);
    var i;
    var width = 100 / colspan;
    for (i = 0; i < list.length; i++) {
        if (i > 0 && i % colspan == 0)
            sl += '</tr><tr>';
        sl += '<td nowrap class="my-link';
        if (node && node.isParent && node.id == list[i].typeid) {
            sl += ' parent-link';
        }
        sl += '" data-typeid="' + list[i].typeid + '" data-linkid="' + list[i].id + '" data-link="' + list[i].url + '" data-name="' + list[i].name + '" title="' + list[i].description + '" style="width:' + width + '%;">';
        sl += '<a href="#"><span id="idCount_' + list[i].id + '" data-count="' + list[i].visitcount + '" class="badge pull-right" title="' + list[i].visitcount + '">' + (list[i].visitcount >= 100 ? '99+' : list[i].visitcount) + '</span>' + list[i].name + '</a></td>';
    }
    if (i % colspan != 0) {
        for (var r = 0; r < colspan - i % colspan; r++) {
            sl += '<td></td>';
        }
    }
    sl += '</tr></table>';
    container.append(sl);

    var _items = $('.my-link', container).click(function (e) {
        var id = $(this).data('linkid');
        var link = $(this).data('link');
        fnOpenUrl(id, link);
    })
    var $idHoverMessage = $("#idHoverMessage");
    _items.hover(function (e) {
        var targ = $(this);
        var id = $(targ).data('linkid');
        var link = $(targ).data('link');
        var name = $(targ).data('name');
        var title = $(targ).attr('title');
        var typeid = $(targ).data('typeid');
        $idHoverMessage.html('[' + name + '] ' + link);
    }, function (e) {

    });

    var menu = $('.link-menu');
    _items.bind("contextmenu", function (e) {
        e.preventDefault();
        var item = $(e.target).closest(".my-link");
        menu.data('target', item);
        menu.menu('show', {
            left: e.pageX,
            top: e.pageY
        });
    });
}

function fnOpenUrl(id, link) {
    var $count = $("#idCount_" + id);

    var visitcount = $count.data("count");

    $count.html((visitcount >= 100 ? '99+' : visitcount + 1)).data("count", visitcount + 1);
    $.post("/api/link/visit", { linkId: id });

    window.open(link, 'link_' + id);
}

function fnRefreshSession() {
    var doRefresh = function () {
        $.post("/api/refresh");
    }
    var timerHandler = undefined;
    var cbxRefresh = $("#idCbxRefresh").change(function () {
        var checked = $(this).prop("checked");
        if (checked) {
            doRefresh();
            timerHandler = setInterval(function () {
                doRefresh();
            }, 10 * 60 * 1000);
        }
        else
            timerHandler && clearInterval(timerHandler);
    });
    if (cbxRefresh.prop("checked"))
        doRefresh();
}

function fnGetColspan(len) {
    var size = 5;
    if (len <= 4) {
        return 4;
    }
    var unit = len % size;
    if (unit == 0)
        return size;
    return size + 1;
}